import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { User } from '@/types'
import Cookies from 'js-cookie'
import { login, getUserInfo, logout } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(Cookies.get('token') || '')
  const userInfo = ref<User | null>(null)
  const permissions = ref<string[]>([])

  // 登录
  const loginAction = async (loginForm: { username: string; password: string }) => {
    try {
      const response = await login(loginForm)
      const data = response.data || response
      token.value = data.accessToken
      Cookies.set('token', data.accessToken, { expires: 7 })
      localStorage.setItem('token', data.accessToken)

      // 如果登录响应中包含用户信息，直接设置
      if (data.user) {
        userInfo.value = data.user
      }
      if (data.permissions) {
        permissions.value = data.permissions
      }

      return data
    } catch (error) {
      throw error
    }
  }

  // 获取用户信息
  const getUserInfoAction = async () => {
    try {
      const response = await getUserInfo()
      const data = response.data || response
      userInfo.value = data.user
      permissions.value = data.permissions || []
      return data
    } catch (error) {
      throw error
    }
  }

  // 登出
  const logoutAction = async () => {
    try {
      await logout()
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      token.value = ''
      userInfo.value = null
      permissions.value = []
      Cookies.remove('token')
      localStorage.removeItem('token')
    }
  }

  // 初始化用户信息
  const initUserInfo = async () => {
    if (token.value) {
      try {
        await getUserInfoAction()
      } catch (error) {
        // 如果获取用户信息失败，清除token
        logoutAction()
      }
    }
  }

  // 检查权限
  const hasPermission = (permission: string) => {
    return permissions.value.includes(permission)
  }

  return {
    token,
    userInfo,
    permissions,
    login: loginAction,
    getUserInfo: getUserInfoAction,
    logout: logoutAction,
    initUserInfo,
    hasPermission
  }
})
